package com.atjg.autocat.main


import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.graphics.drawable.DrawableCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.atjg.autocat.R
import com.atjg.autocat.databinding.ActivityConfigBinding
import com.atjg.autocat.dialog.UpdateDialog
import com.atjg.autocat.serialPort.PortUtils
import com.atjg.autocat.serialPort.PortUtils.Companion.crc16CCITT
import com.atjg.autocat.utils.FileUtils
import com.atjg.autocat.viewModel.MainViewModel
import com.azhon.appupdate.config.UpdateConfiguration
import com.azhon.appupdate.listener.OnDownloadListener
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils
import com.google.gson.internal.LinkedTreeMap
import com.lxj.xpopup.XPopup
import com.zhy.baselibrary.adapter.BaseAdapterHelper
import com.zhy.baselibrary.adapter.recycler.RecyclerAdapter
import com.zhy.baselibrary.base.BaseActivity
import com.zhy.baselibrary.expand.ToastMgr
import com.zhy.baselibrary.shape.RoundTextView
import com.zhy.baselibrary.utils.clickWithTrigger
import java.io.File


class ConfigActivity : BaseActivity<ActivityConfigBinding, MainViewModel>() {
    private var list = ArrayList<List<LinkedTreeMap<String, Any>>>()
    private var taoCanType = "tc1"
    private val shjList by lazy {
        val mlist = ArrayList<String>()
        for (i in 1..60) {
            mlist.add("$i")
        }
        mlist
    }
    @OptIn(ExperimentalStdlibApi::class)
    private val shjAdapter by lazy {
        object : RecyclerAdapter<String>(this, R.layout.adapter_box_item, shjList) {
            @SuppressLint("DefaultLocale", "NotifyDataSetChanged")
            override fun convert(helper: BaseAdapterHelper, item: String, position: Int) {
                val tTitle = helper.getView<RoundTextView>(R.id.tTitle)
                tTitle.text = item
                if (-1 == position) {
                    tTitle.delegate.strokeColor = Color.parseColor("#2C94F8")
                    tTitle.delegate.backgroundColor = Color.parseColor("#2C94F8")
                    tTitle.setTextColor(Color.parseColor("#FFFFFF"))
                } else {
                    tTitle.delegate.strokeColor = Color.parseColor("#333333")
                    tTitle.delegate.backgroundColor = Color.parseColor("#FFFFFF")
                    tTitle.setTextColor(Color.parseColor("#333333"))
                }
                helper.view.clickWithTrigger {
                    //支付完成  开始出货
                    var hex16 ="${position+1}"
                    if (hex16.length == 1) {
                        hex16 = "0$hex16"
                    }
                    val msg = byteArrayOf(
                        0x55,
                        0xAA.toByte(),
                        0x04,
                        0x01,
                        0x06,
                        hex16.toByte(),
                        0x01
                    ).crc16CCITT().toHexString()
                    PortUtils.initSerial().sendHex("/dev/ttyS0",msg,"config-open")
                }
            }
        }
    }

    private val taocanAdapter by lazy {
        object : RecyclerAdapter<List<LinkedTreeMap<String, Any>>>(this, R.layout.adapter_taocan) {
            @SuppressLint("DefaultLocale", "NotifyDataSetChanged")
            override fun convert(
                helper: BaseAdapterHelper,
                item: List<LinkedTreeMap<String, Any>>,
                position: Int
            ) {
                val tTitle = helper.getView<TextView>(R.id.tvTitle)
                when (position) {
                    0 -> {
                        tTitle.text = "套餐一"
                    }

                    1 -> {
                        tTitle.text = "套餐二"
                    }

                    2 -> {
                        tTitle.text = "套餐三"
                    }
                }
                val rvFun = helper.getView<RecyclerView>(R.id.rvFun)
                rvFun.layoutManager = GridLayoutManager(this@ConfigActivity, 10)
                val funAdapter = initFunAdapter()
                rvFun.adapter = funAdapter
                funAdapter.clear()
                funAdapter.addAll(item)
                helper.getView<TextView>(R.id.tvDel).clickWithTrigger {
                    XPopup.Builder(this@ConfigActivity)
                        .maxWidth(ScreenUtils.getScreenWidth() / 3)
                        .asConfirm("提示", "是否确定删除？", "取消", "确定", {
                            list.remove(item)
                            SPUtils.getInstance().put("taocan", GsonUtils.toJson(list))
                            data.remove(item)
                            notifyDataSetChanged()
                        }, {}, false).show()
                }
            }
        }
    }

    override fun initialize() {
        binding.ntbBar.ivLeftImageView.visibility = View.GONE
        initBoxAdapter()
        initSHJAdapter()
        val taocan = SPUtils.getInstance().getString("taocan")
        if (!taocan.isNullOrEmpty()) {
            list = GsonUtils.fromJson<ArrayList<List<LinkedTreeMap<String, Any>>>>(
                taocan,
                ArrayList::class.java
            )
            taocanAdapter.clear()
            taocanAdapter.addAll(list)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initSHJAdapter() {
        binding.rvSHJ.layoutManager = GridLayoutManager(
            this, 10, RecyclerView.VERTICAL, false
        )
        binding.rvSHJ.adapter = shjAdapter
    }
    @SuppressLint("SetTextI18n")
    override fun setListener() {
        super.setListener()
        binding.ntbBar.clickWithTrigger {
            (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
                ?.hideSoftInputFromWindow(binding.ntbBar.windowToken, 0)
        }
        binding.tvFinish.clickWithTrigger {
            ActivityUtils.finishActivity(this)
        }
        binding.rgTaoCan.setOnCheckedChangeListener { group, checkedId ->
            when(checkedId){
                R.id.rbTaoCan1->{
                    taoCanType = "tc1"
                }
                R.id.rbTaoCan2->{
                    taoCanType = "tc2"
                }
                R.id.rbTaoCan3->{
                    taoCanType = "tc3"
                }
            }
        }
        binding.tvSave.clickWithTrigger {
            val time1 = binding.etTime1.text.toString()
            if(time1.isEmpty()){
                ToastMgr.show("请填写清洗时间")
                return@clickWithTrigger
            }
            val time2 = binding.etTime2.text.toString()
            if(time2.isEmpty()){
                ToastMgr.show("请填写沐浴时间")
                return@clickWithTrigger
            }
            val time3 = binding.etTime3.text.toString()
            if(time3.isEmpty()){
                ToastMgr.show("请填写清洗时间")
                return@clickWithTrigger
            }
            val time4 = binding.etTime4.text.toString()
            if(time4.isEmpty()){
                ToastMgr.show("请填写护毛时间")
                return@clickWithTrigger
            }
            val time5 = binding.etTime5.text.toString()
            if(time5.isEmpty()){
                ToastMgr.show("请填写清洗时间")
                return@clickWithTrigger
            }
            val time6 = binding.etTime6.text.toString()
            if(time6.isEmpty()){
                ToastMgr.show("请填写烘干时间")
                return@clickWithTrigger
            }

            val time7 = binding.etTime7.text.toString()
            if(time7.isEmpty()){
                ToastMgr.show("请填写沐浴露时间")
                return@clickWithTrigger
            }

            val time8 = binding.etTime8.text.toString()
            if(time8.isEmpty()){
                ToastMgr.show("请填写护毛素时间")
                return@clickWithTrigger
            }
            SPUtils.getInstance(taoCanType).put("time1",time1.toInt())
            SPUtils.getInstance(taoCanType).put("time2",time2.toInt())
            SPUtils.getInstance(taoCanType).put("time3",time3.toInt())
            SPUtils.getInstance(taoCanType).put("time4",time4.toInt())
            SPUtils.getInstance(taoCanType).put("time5",time5.toInt())
            SPUtils.getInstance(taoCanType).put("time6",time6.toInt())
            SPUtils.getInstance().put("time7",time7.toInt())
            SPUtils.getInstance().put("time8",time8.toInt())
        }

        binding.tvRead.clickWithTrigger {
            val time1 =  SPUtils.getInstance(taoCanType).getInt("time1",-1)
            val time2 =  SPUtils.getInstance(taoCanType).getInt("time2",-1)
            val time3 =  SPUtils.getInstance(taoCanType).getInt("time3",-1)
            val time4 =  SPUtils.getInstance(taoCanType).getInt("time4",-1)
            val time5 =  SPUtils.getInstance(taoCanType).getInt("time5",-1)
            val time6 =  SPUtils.getInstance(taoCanType).getInt("time6",-1)
            val time7 =  SPUtils.getInstance().getInt("time7",-1)
            val time8 =  SPUtils.getInstance().getInt("time8",-1)
            if (time1 != -1){
                binding.etTime1.setText(time1.toString())
            }
            if (time2 != -1){
                binding.etTime2.setText(time2.toString())
            }
            if (time3 != -1){
                binding.etTime3.setText(time3.toString())
            }
            if (time4 != -1){
                binding.etTime4.setText(time4.toString())
            }
            if (time5 != -1){
                binding.etTime5.setText(time5.toString())
            }
            if (time6 != -1){
                binding.etTime6.setText(time6.toString())
            }
            if (time7 != -1){
                binding.etTime7.setText(time7.toString())
            }
            if (time8 != -1){
                binding.etTime8.setText(time8.toString())
            }
        }
        binding.tvDef.clickWithTrigger {
            binding.etTime7.setText("10")
            binding.etTime8.setText("10")
            when (taoCanType) {
                "tc1" -> {
                    binding.etTime1.setText("120")
                    binding.etTime2.setText("60")
                    binding.etTime3.setText("120")
                    binding.etTime4.setText("60")
                    binding.etTime5.setText("420")
                    binding.etTime6.setText("2820")
                }
                "tc2" -> {
                    binding.etTime1.setText("90")
                    binding.etTime2.setText("60")
                    binding.etTime3.setText("90")
                    binding.etTime4.setText("60")
                    binding.etTime5.setText("300")
                    binding.etTime6.setText("1800")
                }
                else -> {
                    binding.etTime1.setText("90")
                    binding.etTime2.setText("60")
                    binding.etTime3.setText("90")
                    binding.etTime4.setText("60")
                    binding.etTime5.setText("300")
                    binding.etTime6.setText("1200")
                }
            }
        }
        binding.tvUpdate.clickWithTrigger {
            showUpdateDialog()
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    private fun initBoxAdapter() {

    }


    override fun onTimeout() {
    }

    private fun initFunAdapter(): RecyclerAdapter<LinkedTreeMap<String, Any>> {
        return object :
            RecyclerAdapter<LinkedTreeMap<String, Any>>(this, R.layout.adapter_item_taocan) {
            @SuppressLint("DefaultLocale", "NotifyDataSetChanged")
            override fun convert(
                helper: BaseAdapterHelper,
                item: LinkedTreeMap<String, Any>,
                position: Int
            ) {
                val tTitle = helper.getView<TextView>(R.id.tvTitle)
                tTitle.text = item["name"] as String
                val ivIcon = helper.getView<ImageView>(R.id.ivIcon)
                val drawable: Drawable? =
                    ContextCompat.getDrawable(ivIcon.context, (item["iconTrue"] as Double).toInt())
                        ?.mutate()
                if (drawable != null) {
                    val wrappedDrawable = DrawableCompat.wrap(drawable)
                    val svgColor = if (item["isOpen"] as Boolean) {
                        Color.parseColor("#F8BCBB")
                    } else {
                        Color.parseColor("#999999")
                    }
                    wrappedDrawable.setTint(svgColor)
                    ivIcon.setImageDrawable(wrappedDrawable)
                } else {
                    ivIcon.setImageResource((item["iconTrue"] as Double).toInt())
                }
            }
        }
    }
    private fun showUpdateDialog() {
        val updata = UpdateDialog(this)
        updata.setContent("有新版本需要下载，欢迎体验新版本")
        updata.hintClose()
        updata.setCanceledOnTouchOutside(false)
        updata.setCancelable(false)
        updata.show()
        updata.setOnUpdataListener(object : UpdateDialog.OnUpdataListener {
            override fun upData() {
                upDataVersion(updata, "https://api.xunmeng.yundougongxiang.com/app-cwxhj-release.apk", "")
            }

            override fun upClose() {
                updata.dismiss()
            }
        })
    }

    private fun upDataVersion(dialog: UpdateDialog, apkUrl: String, version: String) {
        val manager: DownloadManager = DownloadManager.getInstance(this)
        manager.setApkName("cwxhj$version.apk")
            .setDownloadPath(FileUtils.getSandboxCameraOutputPath(this))
            .setApkUrl(apkUrl)
            .setAuthorities("com.atjg.autobox")
            .setSmallIcon(R.mipmap.ic_launcher)
            .download()
        val updateConfiguration = UpdateConfiguration()
        updateConfiguration.isShowNotification = false
        updateConfiguration.isShowBgdToast = false
        updateConfiguration.setEnableLog(false)
        updateConfiguration.setJumpInstallPage(true)
        updateConfiguration.setForcedUpgrade(true)
        updateConfiguration.setOnDownloadListener(object : OnDownloadListener {
            override fun downloading(max: Int, progress: Int) {
                dialog.showProgress((progress.toDouble() / max.toDouble() * 100).toInt())
                if (100 == (progress.toDouble() / max.toDouble() * 100).toInt()) {
                    dialog.dismiss()
                }
            }

            override fun start() {

            }

            override fun done(apk: File?) {
                dialog.dismiss()
                if (apk != null) {
                    installApk(apk)
                }
            }

            override fun cancel() {
                dialog.dismiss()
            }

            override fun error(e: java.lang.Exception?) {
                ToastMgr.show("下载失败，请重试")
                dialog.dismiss()
            }
        })
        manager.configuration = updateConfiguration
    }
    private fun installApk(tmpApk: File): Boolean {
        try {
            val intent = Intent()
            intent.setAction("android.intent.action.VIEW")
            if (Build.VERSION.SDK_INT >= 26) {
                val hasInstallPermission: Boolean = packageManager.canRequestPackageInstalls()
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity()
                    return false
                }
            }
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                val contentUri = FileProvider.getUriForFile(
                    this,
                    "com.atjg.autobox",
                    tmpApk
                )
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(
                    Uri.fromFile(tmpApk),
                    "application/vnd.android.package-archive"
                )
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            startActivity(intent)
            return true
        } catch (e: Exception) {
            e.printStackTrace()

            return false
        }
    }
    private fun startInstallPermissionSettingActivity() {
        val intent = Intent()
        val packageURI = Uri.parse("package:$packageName")
        intent.setData(packageURI)
        if (Build.VERSION.SDK_INT >= 26) {
            intent.setAction("android.settings.MANAGE_UNKNOWN_APP_SOURCES")
        } else {
            intent.setAction("android.settings.SECURITY_SETTINGS")
        }
        startActivity(intent)
    }
}